package com.centanet.framework.service;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.NotificationCompat;
import android.text.TextUtils;

import com.centanet.centalib.R;
import com.centanet.framework.interfaces.IDownloadResult;
import com.centanet.framework.interfaces.IProgressResponseListener;
import com.centanet.framework.model.AppUpdateProgress;
import com.centanet.framework.task.DownloadTask;
import com.centanet.framework.utils.AppUpdateUtil;
import com.centanet.framework.utils.ExternalCacheDirUtil;
import com.centanet.framework.utils.OkHttpUtil;
import com.centanet.framework.utils.ProgressHelper;
import com.centanet.framework.utils.SysUtil;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.OkHttpClient;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

/**
 * apk 下载安装
 */
public class ApkDownloadService extends Service {

    private final static String TAG = "ApkDownloadService";

    private OkHttpClient okHttpClient;
    private NotificationManagerCompat notificationManagerCompat;
    private NotificationCompat.Builder builder;
    private int notificationId;
    private String cacheDir;//保存路径
    private DownloadTask downloadTask;
    private int progress = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        okHttpClient = OkHttpUtil.getOkHttpClient();
        PackageInfo packageInfo = SysUtil.getPackageInfo(this);
        ApplicationInfo applicationInfo = packageInfo.applicationInfo;
        notificationId = applicationInfo.packageName.hashCode();
        cacheDir = ExternalCacheDirUtil.getApkCacheDir();

        notificationManagerCompat = NotificationManagerCompat.from(this);
        builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(getString(applicationInfo.labelRes))
                .setSmallIcon(R.drawable.ic_apk_download)
                .setAutoCancel(false)
                .setWhen(System.currentTimeMillis());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        checkAndDownload();
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        if (downloadTask != null)
            downloadTask.cancel(true);
        super.onDestroy();
    }

    /**
     * 检查、下载
     */
    private void checkAndDownload() {
        String apkName = AppUpdateUtil.getApkName(this);
        String url = AppUpdateUtil.getUpdateUrl(this);
        int versionCode = AppUpdateUtil.getUpdateVerisonCode(this);
        if (TextUtils.isEmpty(cacheDir)) {//SD卡不可用
            builder.setContentText(getString(R.string.sd_unable))
                    .setAutoCancel(true);
            notification();
            stopSelf();
            return;
        }
        if (TextUtils.isEmpty(url) || versionCode <= 1) {
            Logger.t(TAG).e("下载地址为空 or VersionCode<=1");
            stopSelf();
            return;
        }
        final File file = new File(new File(cacheDir), apkName + "-" + versionCode + ".apk");
        if (file.exists()) {//已经下载到本地
            successAndInstall(file);
            EventBus.getDefault().post(new AppUpdateProgress(0, 100));
            return;
        }
        downloadTask = new DownloadTask(ProgressHelper.addProgressResponseListener(okHttpClient, new IProgressResponseListener() {
            @Override
            public void onResponseProgress(long bytesRead, long contentLength, boolean done) {
                Logger.t(TAG).d("progress read : %d - sum : %d - progrss : %d - done : %b", bytesRead, contentLength, bytesRead * 100 / contentLength, done);
                if (done) {//下载完成
                    successAndInstall(file);
                    EventBus.getDefault().post(new AppUpdateProgress(0, 100));
                } else {//正在下载
                    final int current = (int) (bytesRead * 100 / contentLength);
                    if (current > progress || progress == 0) {
                        progress = current;
                        builder.setContentText(getString(R.string.app_update_progress))
                                .setContentInfo(progress + "%")
                                .setProgress(100, progress, false)
                                .setAutoCancel(false);
                        notification();
                        EventBus.getDefault().post(new AppUpdateProgress(1, progress));
                    }
                }
            }
        }), url, file, new IDownloadResult() {
            @Override
            public void result(boolean error) {
                if (error) {//下载失败
                    if (file.exists()) {
                        file.delete();
                    }
                    builder.setContentText(getString(R.string.app_update_error))
                            .setContentInfo("")
                            .setProgress(0, 0, false)
                            .setContentIntent(PendingIntent.getService(ApkDownloadService.this, 0, new Intent(getApplicationContext(), ApkDownloadService.class), PendingIntent.FLAG_CANCEL_CURRENT))
                            .setAutoCancel(true);
                    notification();
                    EventBus.getDefault().post(new AppUpdateProgress(2, 0));
                    stopSelf();
                }
            }
        });
        downloadTask.execute();
    }

    /**
     * 下载成功、安装
     */
    private void successAndInstall(File file) {
        builder.setContentText(getString(R.string.app_update_complete))
                .setContentInfo("")
                .setProgress(0, 0, false)
                .setContentIntent(PendingIntent.getActivity(this, 0, getInstallIntent(file), PendingIntent.FLAG_CANCEL_CURRENT))
                .setAutoCancel(true);
        notification();
        startActivity(getInstallIntent(file));
        stopSelf();
    }

    /**
     * 通知
     */
    private void notification() {
        notificationManagerCompat.notify(notificationId, builder.build());
    }

    /**
     * 安装的Intent
     *
     * @param file apk文件
     * @return Intent
     */
    private Intent getInstallIntent(File file) {
        try {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            return intent;
        } catch (Exception e) {
            e.printStackTrace();
            return new Intent();
        }
    }
}
